var c = document.getElementById('c');
var ctx = c.getContext('2d');
c.width = window.innerWidth * window.devicePixelRatio;
c.height = window.innerHeight * window.devicePixelRatio;

//如何计算图案圆周运动时的位置变化
//  1.知道图案的位置 (x, y)。
//  2.设定每一帧需要旋转的角速度
//  3.公式： newX = x * cos - y * sin; newY = y * cos + x * sin;
//  4.旋转回去: newX = x*cos + y * sin;  newY = y * cos - x * sin;

function Line( x1, y1, x2, y2) {
    this.x1 = x1 || 0;
    this.y1 = y1 || 0;
    this.x2 = x2 || 0;
    this.y2 = y2 || 0;
    this.rotation = 0;
}
Line.prototype = {
    draw: function(ctx) {
        ctx.save();
        ctx.translate(this.x1, this.y1);
        ctx.rotate(this.rotation);
        ctx.strokeStyle = '#333';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(this.x2, this.y2);
        ctx.closePath();
        ctx.stroke();
        ctx.restore();
    }
}

function Ball(x, y, r, color) {
    this.x = x || c.width / 2;
    this.y = y || c.height / 2;
    this.r = r || 25;
    this.speed = {
        x: 0,
        y: 1
    };
    this.color = color || 'red';
}
Ball.prototype = {
    draw: function(ctx) {
        ctx.save();
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
        ctx.closePath();
        ctx.fill();
        ctx.restore();
    }
}

var line = new Line(50, 300, 300, 0);
var ball = new Ball(60, 150, 20, 'red');
var gravity = .2; //重力加速度
var bounce = -.4; //反弹系数
var angleN = 30; //斜面旋转角度
line.rotation = angleN * Math.PI / 180;
var cos = Math.cos(line.rotation);
var sin = Math.sin(line.rotation);

//动画函数
function animate() {
    requestAnimationFrame(animate);
    ctx.clearRect(0, 0, c.width, c.height);

    ball.speed.y += gravity; //一开始，竖直落下

    ball.x += ball.speed.x;
    ball.y += ball.speed.y;

    var x1 = ball.x - line.x1, //计算秋 和 线的相对位置
        y1 = ball.y - line.y1,
        y2 = y1 * cos - x1*sin;

    if( ball.x + ball.r > line.x1 && ball.x - ball.r < line.x2) {
        if(y2 > -ball.r) { //只有当小球与平面接触时才做旋转
            var x2 = x1 * cos + y1 * sin, //旋转后x坐标
                vx1 = ball.speed.x * cos + ball.speed.y * sin,
                vy1 = ball.speed.y * cos + ball.speed.x * sin;
    
            y2 = -ball.r;
            vy1 *= bounce;
    
            //旋转回去
            x1 = x2*cos - y2*sin;
            y1 = y2*cos + x2*sin;
            ball.speed.x = vx1 * cos - vy1 * sin;
            ball.speed.y = vy1 * cos + vx1 * sin;
            ball.x = line.x1 + x1;
            ball.y = line.y1 + y1;
        }
    }


    line.draw(ctx);
    ball.draw(ctx);
}

animate();